<?php
/**
 * Joomla! 1.5 component Joomla Community Polls
 *
 * @version $Id: joomlacommunitypolls.php 2009-08-10 03:45:15 svn $
 * @author Maverick
 * @package Joomla
 * @subpackage Joomla Community Polls
 * @license GNU/GPL
 *
 * The Joomla Community Polls allows the members of the Joomla website to create and manage polls from the front-end.
 * The administrator has the powerful tools provided in the back-end to manage the polls published by all users.
 */

// no direct access
defined('_JEXEC') or die('Restricted access');

jimport('joomla.application.component.model');

/**
 * Joomla Community Polls Component Joomla Community Polls Model
 *
 * @author      maverick
 * @package		Joomla
 * @subpackage	Joomla Community Polls
 * @since 1.5
 */
class JoomlaCommunityPollsModelPolls extends JModel {

    var $_error = '';
    
    /**
	 * Constructor
	 */
	function __construct() {
		parent::__construct();
    }

    function getPollsList(){
    	global $mainframe, $option;
		$db =& JFactory::getDBO();
        $user =& JFactory::getUser();
        
		$filter_order		= $mainframe->getUserStateFromRequest( "$option.filter_order",		'filter_order',		'p.id',	'cmd' );
		$filter_order_Dir	= $mainframe->getUserStateFromRequest( "$option.filter_order_Dir",	'filter_order_Dir',	'DESC', 'word' );
		$limit              = $mainframe->getUserStateFromRequest( 'global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int' );
		$limitstart         = $mainframe->getUserStateFromRequest( $option.'.limitstart', 'limitstart', 0, 'int' );
		$orderby            = ' ORDER BY '. $filter_order .' '. $filter_order_Dir;
        
		$query = 'SELECT COUNT(p.id) FROM ' . TABLE_JCP_POLLS . ' AS p WHERE p.published=' . STATUS_PUBLISHED;
		$db->setQuery( $query );
		$total = $db->loadResult();
        
		jimport('joomla.html.pagination');
		$pagination = new JPagination( $total, $limitstart, $limit );
        $eligibility = '';
        if($user && $user->id > 0){
            $eligibility = ', (SELECT COUNT(*) FROM ' . TABLE_JCP_VOTES .
                ' WHERE poll_id=p.id AND voted_by=' . $user->id . ') AS voted';
        }
        
        $query = 'SELECT p.id, p.title, p.alias, p.votes, p.created, u.username' . $eligibility  .
            ' FROM ' . TABLE_JCP_POLLS . ' p LEFT JOIN #__users u ON p.created_by=u.id ' .
            ' WHERE p.published=' . STATUS_PUBLISHED . $orderby;
		$db->setQuery( $query, $pagination->limitstart, $pagination->limit );
		$rows = $db->loadObjectList();
//echo $query;
		$lists['order_Dir']	= $filter_order_Dir;
		$lists['order']		= $filter_order;

        $result->items = $rows;
        $result->lists = $lists;
        $result->pagination = $pagination;
        
        return $result;
    }

    function castVote(){
		$db =& JFactory::getDBO();
		$user =& JFactory::getUser();
        $poll_id = JRequest::getVar('poll_id',0,'post','INTEGER');
        $option_id = JRequest::getVar('option_id',0,'post','INTEGER');

        $eligible = true;
        if($user && $user->id > 0){
            $query = 'SELECT COUNT(*) FROM ' . TABLE_JCP_VOTES . ' WHERE poll_id=' .
                $poll_id . ' AND voted_by=' . $user->id;
            $db->setQuery( $query );
            $count = $db->loadResult();
            if($count > 0){
                $eligible = false;
            }
        }

        if($eligible){
            $query = 'UPDATE ' . TABLE_JCP_POLLS . ' SET votes=votes+1 WHERE id=' . $poll_id;
            $db->setQuery( $query );
            if(!$db->query()){
                $this->_error = JText::_('MSG_ERROR_ON_VOTE');
                return false;
            }
        
            $query = 'UPDATE ' . TABLE_JCP_OPTONS . ' SET votes=votes+1 WHERE id=' .
                $option_id . ' AND poll_id=' . $poll_id;
            $db->setQuery( $query );
            if(!$db->query()){
                $this->_error = JText::_('MSG_ERROR_ON_VOTE');
                return false;
            }
            
            if($user && $user->id > 0){
                $query = 'INSERT INTO ' . TABLE_JCP_VOTES . '(poll_id, voted_by, voted_on) VALUES' .
                    '(' . $poll_id . ',' . $user->id . ', NOW())';
                $db->setQuery( $query );
                if(!$db->query()){
                    $this->_error = JText::_('MSG_ERROR_ON_VOTE');
                    return false;
                }
            }

            return true;
        }else{
            $this->_error = JText::_('MSG_ALREADY_VOTED');
            return false;
        }
    }

    function getPollData(){
        global $mainframe, $option;
        
        $db =& JFactory::getDBO();
        $user =& JFactory::getUser();
        $poll_id = JRequest::getVar('poll_id',0,'','INTEGER');

        $query = 'SELECT p.id, p.title, p.alias, p.votes, p.published, p.created, u.username' .
            ' FROM ' . TABLE_JCP_POLLS . ' p LEFT JOIN #__users u ON p.created_by=u.id' .
            ' WHERE p.id=' . $poll_id;
        $db->setQuery($query);
        $poll = $db->loadObject();

        if(isset($poll)){
            $query = 'SELECT id, title, votes FROM ' . TABLE_JCP_OPTONS . ' WHERE poll_id=' . $poll_id;
            $db->setQuery($query);
            $options = $db->loadObjectList();
            if(!isset($options)){
                $this->_error = JText::_('MSG_NO_OPTIONS');
                return false;
            }
            $poll->options = $options;
            $poll->eligible = true;
            
            $cookieName	= JUtility::getHash( $mainframe->getName() . COOKIE_PREFIX . $poll_id );
            $voted = JRequest::getVar( $cookieName, '0', 'COOKIE', 'INT');
            if($voted){
                $poll->eligible = false;
            }
            if($poll->eligible){
                $query = 'SELECT COUNT(*) FROM ' . TABLE_JCP_VOTES . ' WHERE poll_id=' .
                    $poll_id . ' AND voted_by=' . $user->id;
                $db->setQuery($query);
                $count = $db->loadResult();
                if($count > 0){
                    $poll->eligible = false;
                }
            }
        }else{
            $this->_error = JText::_('MSG_POLL_NOT_EXIST');
            return false;
        }

        return $poll;
    }

    function getError(){
        return $this->_error;
    }
}
?>